import {
  Component, OnInit, Output, Input, EventEmitter, ViewChild, TemplateRef, HostBinding, ViewEncapsulation, NgZone, OnDestroy
} from '@angular/core';
import { NotifyService } from '@farris/ui-notify';
import { TreeNode } from '@farris/ui-treetable';
import { ElementPropertyConfig, PropertyChangeObject } from '@farris/ide-property-panel';
import { SchemeFeatureService } from './query-scheme.service';
import { cloneDeep } from 'lodash-es';
import { MessagerService } from '@farris/ui-messager';
import { FormSchemaEntityField$Type, FormSchemaEntityFieldTypeName, DesignViewModelService, DomService } from '@farris/designer-services';
import { MultiSelectComponent } from '@farris/ui-multi-select';
import { Subscription } from 'rxjs';
import { QuerySchemaFieldCreator } from './query-data/field-control-data';

@Component({
  selector: 'app-query-scheme-fields-editor',
  templateUrl: './query-scheme-fields-editor.component.html',
  providers: [SchemeFeatureService],
  styleUrls: ['./query-scheme-fields-editor.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class QuerySchemeFieldsEditorComponent implements OnInit, OnDestroy {
  @Output() closeModal = new EventEmitter<any>();
  @Output() submitModal = new EventEmitter<any>();
  @Input() value;
  @Input() editorParams = { viewModelId: '', presetFieldConfigs: [] };

  /** 是否显示属性面板 */
  @Input() showPropertyPanel = true;

  @ViewChild('footer') modalFooter: TemplateRef<any>;
  modalConfig = {
    title: '筛选方案字段编辑器',
    width: 1200,
    height: 700,
    showButtons: true,
    showMaxButton: true
  };
  // 筛选方案定义的字段
  fieldConfigs = [];

  // 预设的字段
  presetFieldConfigs = [];

  // 左侧树表数据
  treeData: TreeNode[] = [];

  // 当前可选的所有字段ID
  treeNodeIds: string[] = [];

  // 选中的字段
  selectedFieldIds = [];

  // 右侧选中行对应的schema字段信息
  selectedSchemaField;


  // 属性面板配置
  propertyConfig: ElementPropertyConfig[];

  // 属性面板值
  propertyData;

  // 大数值类型的字段ID--用于schema变更后修改数字控件的isBigNumber属性
  // bigNumberFields = [];

  /** 平铺的树表数据 */
  plainTreeNodes = [];

  @HostBinding('class')
  class = 'd-flex  h-100';

  @ViewChild(MultiSelectComponent) multiSelectCmp: MultiSelectComponent;

  timer: any;

  private triggerSaveAndCloseEditorSub: Subscription;

  /** 记录编辑器刚打开时的DOM actions数据。编辑器内部交互面板在操作过程中可能会修改actions节点，导致点击【取消】按钮时无法还原actions数据。所以这里记录一份原始数据，方便还原。 */
  private previousActions: any[];

  /** 记录编辑器刚打开时的DOM viewmodels数据。编辑器内部交互面板在操作过程中可能会修改viewmodels节点，导致点击【取消】按钮时无法还原viewmodels数据。所以这里记录一份原始数据，方便还原。 */
  private previousViewModels: any[];


  constructor(
    private dgVMService: DesignViewModelService, private notifyService: NotifyService,
    private schemeFeatureServ: SchemeFeatureService, private msgService: MessagerService,
    private domService: DomService,
    private ngZone: NgZone) { }

  ngOnInit(): void {
    if (!this.editorParams || !this.value) {
      return;
    }
    this.fieldConfigs = cloneDeep(this.value);
    this.treeData = this.dgVMService.getAllFields2TreeByVMId(this.editorParams.viewModelId);
    this.plainTreeNodes = [];
    this.filterAllowedType(this.treeData);

    this.presetFieldConfigs = this.editorParams.presetFieldConfigs;

    this.selectedFieldIds = this.value.map(v => v.id);

    this.filterSchemFields();

    // 触发保存并关闭当前窗口
    this.triggerSaveAndCloseEditorSub = this.schemeFeatureServ.triggerSaveAndCloseEditor.subscribe(() => {
      this.clickConfirm();
    });

    // 默认选中第一行
    if (this.selectedFieldIds.length && this.multiSelectCmp['selectItem']) {
      this.ngZone.runOutsideAngular(() => {
        this.timer = setTimeout(() => {
          this.multiSelectCmp['selectItem'](this.selectedFieldIds[0]);
        });
      });
    }


    this.previousActions = cloneDeep(this.domService.module.actions);
    this.previousViewModels = cloneDeep(this.domService.module.viewmodels);
  }

  ngOnDestroy(): void {
    this.schemeFeatureServ.triggerSaveAndCloseEditor.unsubscribe();

    if (this.triggerSaveAndCloseEditorSub) {
      this.triggerSaveAndCloseEditorSub.unsubscribe();
    }

    if (this.timer) {
      clearTimeout(this.timer);
    }

  }

  /**
   * 过滤筛选方案支持的字段
   * @param treeData 树数据
   */
  filterAllowedType(treeData: TreeNode[]) {
    treeData.forEach(treeNode => {
      this.plainTreeNodes.push(treeNode.data);
      if (treeNode.data.$type === FormSchemaEntityField$Type.SimpleField) {
        if (!this.schemeFeatureServ.allowedFieldType.includes(treeNode.data.type.name)) {
          treeNode.selectable = false;
        } else {
          this.treeNodeIds.push(treeNode.data.id);
          // if (treeNode.data.type.name === FormSchemaEntityFieldTypeName.BigNumber) {
          //   this.bigNumberFields.push(treeNode.data.id);
          // }
        }
      }
      if (treeNode.children && treeNode.children.length > 0) {
        this.filterAllowedType(treeNode.children);
      }
    });
  }
  filterSchemFields() {
    const removedFields = [];
    this.selectedFieldIds.forEach(id => {
      const field = this.fieldConfigs.find(f => f.id === id);
      if (!this.treeNodeIds.includes(id)) {
        // schema中已移除的字段
        removedFields.push(field.name);
        this.fieldConfigs = this.fieldConfigs.filter(f => f.id !== id);
        this.selectedFieldIds = this.selectedFieldIds.filter(fid => fid !== id);
        return;
      }
      if (!field.control || !field.control.controltype) {
        return;
      }
      const schemaField = this.plainTreeNodes.find(node => node.path === field.labelCode);
      if (!schemaField) {
        return;
      }
      // 补充大数字值
      if (field.control.controltype.includes('number')) {
        field.control.isBigNumber = schemaField.type.name === FormSchemaEntityFieldTypeName.BigNumber;
      }
      // 日期类型的字段，配置为日期区间控件或日期时间区间控件，需要补充开始字段和结束字段
      if (['date'].includes(field.control.controltype)) {
        if ([FormSchemaEntityFieldTypeName.Date, FormSchemaEntityFieldTypeName.DateTime].includes(schemaField.type.name)) {
          field.control.startFieldCode = field.control.startFieldCode ? field.control.startFieldCode : schemaField.path;
          field.control.endFieldCode = field.control.endFieldCode ? field.control.endFieldCode : schemaField.path;
        }
      }
    });
    if (removedFields.length > 0) {

      this.ngZone.runOutsideAngular(() => {
        setTimeout(() => {
          this.msgService.warning('已选择字段【' + removedFields.toString() + '】已移除、变更或暂不支持添加，点击确定后将自动删除字段');
        });
      });
    }
  }

  /**
   * 改变选中字段事件
   * @param e 选中的行数据
   */
  changeSelectField(e: any[]) {
    if (!e) {
      return;
    }
    const fieldConfigs = [];
    if (e.length === 0) {
      this.propertyConfig = [];
      this.fieldConfigs = [];
      return;
    }
    e.forEach(data => {
      const co = this.fieldConfigs.find(c => c.id === data.id);
      if (co) {
        fieldConfigs.push(co);
      } else {
        const newConfig = QuerySchemaFieldCreator.getSolutionField(data);
        if (newConfig.control) {
          fieldConfigs.push(newConfig);
        }
      }
    });
    this.fieldConfigs = fieldConfigs;


    if (this.selectedSchemaField && !fieldConfigs.find(f => f.id === this.selectedSchemaField.id)) {
      this.propertyConfig = [];
    }

    this.schemeFeatureServ.fieldConfigs = this.fieldConfigs;
  }

  /**
   * 切换右侧行
   * @param e 行数据
   */
  changeRightSelect(e) {
    if (!e.selected || !e.data) {
      return;
    }
    this.triggerShowPropertyPanel(e.data);
  }

  triggerShowPropertyPanel(rowData: any) {
    this.selectedSchemaField = rowData;

    this.propertyData = this.fieldConfigs.find(f => f.id === rowData.id);
    this.propertyConfig = this.schemeFeatureServ.getPropertyConfig(rowData, this.propertyData,
      this.editorParams.viewModelId, this.fieldConfigs);

  }


  propertyChanged(changeObject: PropertyChangeObject) {

    // 修改控件名称后，要同步控件的路径信息,用于交互面板的显示
    if (changeObject.propertyID === 'name') {

      this.domService.controlBasicInfoMap.set(this.propertyData.id, {
        showName: changeObject.propertyValue,
        parentPathName: `筛选方案 > ${changeObject.propertyValue}`
      });
    }


  }

  submitPropertyModal(data: { changeObject: PropertyChangeObject, parameters: any }) {
    const changeObject = data.changeObject;
    // 交互面板变更后，同步控件的路径信息
    if (changeObject.categoryId === 'eventsEditor') {

      this.domService.controlBasicInfoMap.set(this.propertyData.id, {
        showName: this.propertyData.name,
        parentPathName: `筛选方案 > ${this.propertyData.name}`
      });
    }

  }
  clickCancel() {
    this.domService.module.actions = this.previousActions;
    this.domService.module.viewmodels = this.previousViewModels;

    this.closeModal.emit();
  }

  clickConfirm() {
    if (this.fieldConfigs.length === 0) {
      this.notifyService.warning('请选择字段');
      return;
    }
    if (this.presetFieldConfigs && this.presetFieldConfigs.length > 0) {
      // 同步移除的字段
      const fieldIds = this.fieldConfigs.map(f => f.id);
      this.presetFieldConfigs = this.presetFieldConfigs.filter(pf => fieldIds.includes(pf.id));
      // 同步修改的属性
      this.presetFieldConfigs.forEach(presetF => {
        const field = this.fieldConfigs.find(f => f.id === presetF.id);
        Object.assign(presetF, field);
      });

    }
    this.submitModal.emit({ value: this.fieldConfigs, parameters: this.presetFieldConfigs });
  }
}
